import app from '../app.js';
import config from '../config.js';
import Base_tools_class from '../core/base-tools.js';
import { getBackgroundColorByCanvas, rgbaToObject } from '../utils.js'
import { message, Modal } from 'antd';
class Background_removal extends Base_tools_class {
  constructor(ctx) {
    super();
    this.ctx = ctx;
    this.name = 'background_removal';
  }

  load() {
    document.addEventListener('keydown', (e) => {
      if (config.TOOL.name != this.name) return
      var code = e.keyCode;
      if (code == 13) {
        this.background_removal()
      }
    }, false);
  }

  /**
   * 启动去背透功能
   */
  background_removal() {

    if (!config.layer || !config.layer.link) {
      message.warning('当前没有选中的图层');
      return;
    }

    //get canvas from layer
		var canvas = this.Base_layers.convert_layer_to_canvas(null, true);
		var ctx = canvas.getContext("2d");
    const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imgData.data;

    // 目标背景颜色（获取图片背景色）
    const targetColor = rgbaToObject(getBackgroundColorByCanvas(this.ctx))
    // 容差范围
    const tolerance = config.TOOL.attributes.power;

    // 遍历每个像素
    for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];

        // 判断像素颜色是否在容差范围内
        if (
            Math.abs(r - targetColor.r) <= tolerance &&
            Math.abs(g - targetColor.g) <= tolerance &&
            Math.abs(b - targetColor.b) <= tolerance
        ) {
            data[i + 3] = 0;
            // 替换背景色
            data[i] = targetColor.r;     // 红色通道
            data[i + 1] = targetColor.g; // 绿色通道
            data[i + 2] = targetColor.b; // 蓝色通道
            data[i + 3] = 255; // 保持不透明
        }
    }

    // 将修改后的图像数据绘制回画布
    ctx.putImageData(imgData, 0, 0);

    if (config.layer.type != null) {
			//update
			app.State.do_action(
				new app.Actions.Bundle_action('background_removal', 'Background_removal Tool', [
					new app.Actions.Update_layer_image_action(canvas)
				])
			);
		}
  }



  /**
   * 激活工具时触发
   */
  onClickFix() {
    this.background_removal();
  }
}

export default Background_removal;